package org.javanile.sms.demo;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import org.javanile.sms.Server;

/**
 * An example MIDlet to send text via an SMS MessageConnection
 */
public class MIDletDemo2 extends MIDlet implements CommandListener {

	Server sms;

	/** user interface command for indicating Exit request. */
    Command exitCommand = new Command("Exit", Command.EXIT, 2);
	
	/** user interface command for proceeding to the next screen */
    Command okCommand = new Command("OK", Command.OK, 1);

    /** current display. */
    Display display;

    /** Area where the user enters the phone number to send the message to */
    TextBox destinationAddressBox;
	Form form;
	TextField number;
	TextField message;

    public MIDletDemo2() {
        
		
        display = Display.getDisplay(this);

		number	= new TextField("Number", null, 32, TextField.ANY);
		message = new TextField("Message", null, 32, TextField.ANY);


		form = new Form("Demo 1");
		
		form.append(number);
		form.append(message);

		destinationAddressBox = new TextBox("Destination Address?", null, 256, TextField.PHONENUMBER);
        form.addCommand(exitCommand);
		form.addCommand(okCommand);
        form.setCommandListener(this);

		
		sms = new Server(this);
    }

    /**
     * startApp should return immediately to keep the dispatcher
     * from hanging.
     */
    public void startApp() {

		display.setCurrent(form);

		sms.start();
		sms.receive(new Server.Incoming() {
			public void received(String msg) {
				//orm.append();
			}
		});
    }

    /**
     * Remember what screen is showing
     */
    public void pauseApp() {
        //resumeScreen = display.getCurrent();
    }

    /**
     * Destroy must cleanup everything.
     * @param unconditional true if a forced shutdown was requested
     */
    public void destroyApp(boolean unconditional) {
		sms.stop();
    }

    /**
     * Respond to commands, including exit
     * @param c user interface command requested
     * @param s screen object initiating the request
     */
    public void commandAction(Command c, Displayable s) {
        try {
            if ((c == exitCommand) || (c == Alert.DISMISS_COMMAND)) {
                destroyApp(false);
                notifyDestroyed();
            } else if (c == okCommand) {
                promptAndSend();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Prompt for and send the message
     */
    private void promptAndSend() {
        String address = number.getString();
        String statusMessage = message.getString();
        sms.send(address,statusMessage);
    }
}
